from wordcloud import WordCloud
import matplotlib.pyplot as plt
import jieba
import pandas as pd

# 仅保留微软雅黑字体，避免因缺少其他字体报错
plt.rcParams["font.family"] = ["SimHei"]
plt.rcParams["axes.unicode_minus"] = False

file_path_clear='../../data/cleared data/'
file_path_image='../../data/image/'
def customer_comment_word_cloud():
    # 1. 读取数据文件
    df = pd.read_excel(file_path_clear+'餐饮连锁品牌数据_顾客评价4_cleaned.xlsx')
    comment_text = df['评价内容'].dropna().str.cat(sep=' ')  # 合并所有有效评价

    # 2. 自定义词典：添加带频率的自定义词，确保识别“态度好”等短语
    jieba.add_word("态度好", freq=1000)
    jieba.add_word("态度差", freq=1000)
    jieba.add_word("上菜快", freq=1000)
    jieba.add_word("上菜慢", freq=1000)
    jieba.add_word("味道好", freq=1000)
    jieba.add_word("味道差", freq=1000)
    jieba.add_word("分量足", freq=1000)
    jieba.add_word("分量少", freq=1000)

    # 3. 分词（精确模式）
    seg_list = jieba.cut(comment_text, cut_all=False)
    seg_text = " ".join(seg_list)

    # 4. 调整停用词
    stopwords = {"的", "是", "可以", "一种", "还有", "这个", "那个", "这里", "那里", "自己", "他们", "我们", "你们",
                 "大家", "有些", "比较", "非常", "感觉", "觉得", "应该", "能够", "会", "就", "都", "很", "还", "也",
                 "又", "只", "更", "最", "挺", "太", "真"}

    # 5. 生成词云
    font_path = "C:\\WINDOWS\\Fonts\\MSYH.TTC"  # 微软雅黑字体路径（Windows系统默认存在）
    wc = WordCloud(
        font_path=font_path,
        background_color="white",
        width=1000,
        height=600,
        max_words=150,
        stopwords=stopwords,
        max_font_size=120,
        colormap="viridis"
    ).generate(seg_text)

    # 6. 显示并保存词云
    plt.figure(figsize=(12, 8))
    plt.imshow(wc, interpolation='bilinear')
    plt.axis("off")
    plt.title('餐饮连锁品牌顾客评价词云（用于优化菜品与服务）', fontsize=16, fontweight='bold')
    plt.tight_layout()
    wc.to_file(file_path_image+'顾客评价词云图.png')
    plt.show()


# 调用函数
customer_comment_word_cloud()